#include <utils/Log.h>
#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <binder/MemoryBase.h>
#include <binder/MemoryHeapBase.h>
#include "android_runtime/AndroidRuntime.h"
#include "JNIHelp.h"
#include "jni.h"
#include <binder/Parcel.h>
#include <stdio.h>
#include <assert.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <utils/threads.h>
#include "android_util_Binder.h"
#include<unistd.h>
#include <sys/ioctl.h>

using namespace android;

#undef LOG_TAG
#define LOG_TAG "BLUETOOTH_JNI_VOLUME"

#define VOLUME_DEVICE_NAME "/proc/bt_vol/volume"

static int g_fd = -1;

static jboolean set_volume(JNIEnv *env, jobject object, jstring buf_volume)
{
	int fd = -1;
	int len;
	const char *volume;

	volume = env->GetStringUTFChars(buf_volume, NULL);
	ALOGE("set bluetooth volume volue is  %s\n", volume);



	fd = open(VOLUME_DEVICE_NAME, O_RDWR);
	if (fd < 0) {
		ALOGE("Couldn't find or open /proc/bt_vol/volume\n");
		return false;
	}

	len = write(fd,volume,sizeof(volume));
	if(len > 0){
		ALOGE("set bluetooth volume success!!!\n");
		close(fd);
		return true;
	}else {
		ALOGE("set bluetooth volume fail!!!\n");
		close(fd);
		return false;
	}

	return 1;

}

static const char* const kClassPathName = "launcher/simple/android/woblog/cn/system/InCallManager";

static JNINativeMethod gMethods[] = {
    {"bluetooth_set_volume","(Ljava/lang/String;)Z",(void *) set_volume},
};

static int register_android_mmi(JNIEnv *env)
{
  return AndroidRuntime::registerNativeMethods(env, kClassPathName, gMethods, NELEM(gMethods));
}


jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
	JNIEnv* env = NULL;
	jint result = -1;

	ALOGE("JNI_OnLoad\n");

	if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
	{
	  ALOGE("ERROR: GetEnv failed\n");
	  return result;
	}
	assert(env != NULL);

	if (register_android_mmi(env) < 0)
	{
	  ALOGE("ERROR: VOLUME native registration failed\n");
	  return result;
	}

	result = JNI_VERSION_1_4;
	
	return result;
}
